/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.traps;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import soot.Body;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.Trap;
import soot.jimple.NopStmt;
import soot.jimple.toolkits.scalar.NopEliminator;
import soot.util.Chain;

import br.ufpe.cin.imlm2.jbeat.soot.common.SceneWrapper;

/**
 * Removes empty traps or 'nop' instructions!
 * 
 * @author Irineu
 * 
 */
public class EmptyTrapRemover extends SceneTransformer {

	private void removeEmptyTraps(Body b) {
		Chain<Trap> traps = b.getTraps();
		Iterator<Trap> trapsIt = traps.snapshotIterator();
		boolean hasNops = false;
		while (trapsIt.hasNext()) {
			Trap next = trapsIt.next();
			if (next.getBeginUnit().equals(next.getEndUnit())) {
				traps.remove(next);
			}
			if (next.getHandlerUnit() instanceof NopStmt)
				hasNops = true;
		}
		if (hasNops)
			NopEliminator.v().transform(b);
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void internalTransform(String phaseName, Map options) {
		System.err.println("Beginning empty traps removal");
		Long startTime = System.currentTimeMillis();
		Collection<SootMethod> concreteOnes = SceneWrapper.getConcreteMethods();
		for (SootMethod sootMethod : concreteOnes) {
			this.removeEmptyTraps(sootMethod.retrieveActiveBody());
		}
		System.err.println("Empty traps removal finished in "
				+ (System.currentTimeMillis() - startTime) + "ms");
	}

}
